﻿using System.Collections;
using UnityEngine;

namespace XLua_Ki
{
    /// 加载UI的Panel
    public class PanelManager_Ki : MonoBehaviour
    {
        private Transform canvas_Transfrom;  //[canvas要添加一个Tag "MainCanvas(默认)"--AppConst设置]
        public Transform Canvas_Transfrom
        {
            get
            {
                if (canvas_Transfrom == null)
                {
                    GameObject m_Canvas = GameObject.FindWithTag(AppConst.canvasTagName);
                    if (m_Canvas != null) canvas_Transfrom = m_Canvas.transform;
                }
                return canvas_Transfrom;
            }
        }

        public void CreatePanel(string name, XLua.LuaFunction luaFunction)
        {
            StartCoroutine(OnCreatePanel(name, luaFunction));
        }

        IEnumerator OnCreatePanel(string name, XLua.LuaFunction luaFunction)
        {
            var assetName = name.ToLower();  

            GameObject go = null;
            GameObject obj = null;
            if (GameManager_Ki.Instance.GetResourcesManager_Ki().Prefabs_AB_GAME.TryGetValue(assetName, out go)){
                //..
            }else{
                var bundleName = BundleRequest.MatchBundleName(name);

                AssetBundle ab = null;
                if (GameManager_Ki.Instance.GetResourcesManager_Ki().Bundles_AB_GAME.TryGetValue(bundleName, out ab))
                {
                    go = ab.LoadAsset<GameObject>(name);
                }
            }

            obj = GameObject.Instantiate<GameObject>(go);
            obj.transform.SetParent(Canvas_Transfrom);
            obj.transform.localScale = Vector3.one;
            obj.transform.localPosition = Vector3.zero;
            obj.AddComponent<MinikimmyLuaBehavoiur>().OnAwake(name);

            yield return null;
            if (luaFunction != null) luaFunction.Call(obj);
        }
    }
}
